<?php
require_once(SITE_ROOT . 'class/db/DB.class.php');
require_once(SITE_ROOT . 'class/bean/Flag.class.php');
require_once(SITE_ROOT . 'class/bean/Team.class.php');
require_once(SITE_ROOT . 'class/bean/Country.class.php');

class DBFlag {
	
	public function getFlagsByTeam($team) {
		$db = new DB();
		$connection = $db->connect();
		
		if ($stmt = $connection->prepare('SELECT `country#`, `team#`, `visited`, `hosted` FROM `tflag` WHERE `team#` = ? ORDER BY `country#`')) {
			$stmt->bind_param('i', $team->getTeamID());
			$stmt->execute();
			$stmt->bind_result($countryID, $teamID, $visited, $hosted);
			
			$flags = new ArrayObject();
			
			while ($stmt->fetch()) {
				$flag = new Flag();
				
				$country = new Country();
				$country->setCountryID($countryID);
				
				$flag->setCountry($country);
				$flag->setVisited($visited);
				$flag->setHosted($hosted);
				
				$flags->append($flag);
			}			
			$stmt->close();
			$db->disconnect();
			
			return $flags;
		}
	}
	
	public function saveFlags($team) {
		$db = new DB;
		$connection = $db->connect();
		
		$flags = $team->getFlags();
		
		if ($stmt = $connection->prepare('INSERT INTO `tflag` (`country#`, `team#`, `visited`, `hosted`) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE `visited`=VALUES(`visited`), `hosted`=VALUES(`hosted`)')) {
			foreach ($flags as $flag) {
				if ($flag->hasVisited() || $flag->hasHosted()) {
					$stmt->bind_param('iiss', $countryID, $teamID, $visited, $hosted);
				
					$countryID = $flag->getCountry()->getCountryID();
					$teamID = $team->getTeamID();
					$visited = $flag->hasVisited();
					$hosted = $flag->hasHosted();
				
					$stmt->execute();
				}				
			}
			$stmt->close();
			$db->disconnect();
		}
	}
	
	public function deleteFlagsByTeamID($teamID) {
		$db = new DB;
		$connection = $db->connect();
		
		if ($stmt = $connection->prepare('DELETE FROM `tflag` WHERE `team#` = ?')) {
			$stmt->bind_param('i', $teamID);
			
			$stmt->execute();
			
			$stmt->close();
			$db->disconnect();
		}
	}
	
}

?>